package com.uuah.server.util.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.w3c.dom.Element;

import com.uuah.server.config.spring.parsers.AbstractUuahBeanDefinitionParser;
import com.uuah.utils.StringUtils;
import com.uuah.utils.XMLUtils;

/**
 * These only depend on standard (JSE) XML classes and are used by Spring config
 * code. For a more extensive (sub-)class, see the XMLUtils class in the XML
 * module.
 */
public class SpringXMLUtils extends XMLUtils {

	private static final Logger logger = LoggerFactory.getLogger(SpringXMLUtils.class);

	public static final String UUAH_DEFAULT_NAMESPACE = "http://developer.uuah.com/schema/uuah/core";

	public static final String UUAH_NAMESPACE_PREFIX = "http://developer.uuah.com/schema/uuah/";

	public static boolean isUuahNamespace(Element element) {
		String ns = element.getNamespaceURI();
		return ns != null && ns.startsWith(UUAH_NAMESPACE_PREFIX);
	}

	public static boolean isBeansNamespace(Element element) {
		String ns = element.getNamespaceURI();
		return ns != null
				&& ns.equals(BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI);
	}

	public static String getNameOrId(Element element) {
		String id = element
				.getAttribute(AbstractUuahBeanDefinitionParser.ATTRIBUTE_ID);
		String name = element
				.getAttribute(AbstractUuahBeanDefinitionParser.ATTRIBUTE_NAME);
		if (StringUtils.isBlank(id)) {
			if (StringUtils.isBlank(name)) {
				return "";
			} else {
				return name;
			}
		} else {
			if (!StringUtils.isBlank(name) && !name.equals(id)) {
				logger.warn("Id (" + id + ") and name (" + name
						+ ") differ for " + elementToString(element));
			}
			return id;
		}
	}

}
